package com.whz.governance.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author whz
 */
@Slf4j
public class GenericObjectUtils extends ObjectUtils {

    public static byte[] objToByteArray(Object obj) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(outputStream)) {
            oos.writeObject(obj);
            oos.flush();
            return outputStream.toByteArray();
        } catch (Exception exception) {
            log.error("", exception);
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public static <T> T byteArrayToObj(byte[] obj) {
        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(obj);
             ObjectInputStream oos = new ObjectInputStream(inputStream)) {
            return (T) oos.readObject();
        } catch (Exception exception) {
            log.error("", exception);
        }
        return null;
    }

    public static String objToString(Object obj) {
        byte[] bytes = objToByteArray(obj);
        if (bytes == null || bytes.length == 0) {
            return "";
        }
        return new String(Base64.getEncoder().withoutPadding().encode(bytes), StandardCharsets.UTF_8);
    }

    public static <T> T stringToObj(final String content) {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        return byteArrayToObj(Base64.getDecoder().decode(content.getBytes(StandardCharsets.UTF_8)));
    }
}
